<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="任务名称" prop="nodeName">
        <el-input
          v-model="queryParams.nodeName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程状态" prop="flowStatus">
        <el-select v-model="queryParams.flowStatus" placeholder="请选择流程状态" clearable>
          <el-option
            v-for="dict in flow_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审批时间" prop="createTime">
        <el-date-picker
          clearable size="small"
          v-model="queryParams.createTime"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择创建时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 流程实例表格 -->
    <el-table :data="instanceList" v-loading="loading">
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" width="55" align="center">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="流程实例id" align="center" prop="instanceId" show-overflow-tooltip />
      <el-table-column label="流程名称" align="center" prop="flowName" show-overflow-tooltip />
      <el-table-column label="任务名称" align="center" prop="nodeName" show-overflow-tooltip />
      <el-table-column label="审批人" align="center" prop="approver" show-overflow-tooltip />
      <el-table-column label="流程状态" align="center" prop="flowStatus" show-overflow-tooltip>
        <template #default="{ row }">
          <dict-tag :options="flow_status" :value="row.flowStatus" />
        </template>
      </el-table-column>
      <el-table-column label="审批时间" align="center" prop="createTime" width="160" show-overflow-tooltip>
        <template #default="{ row }">
          <span>{{ parseTime(row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" fixed="right" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button
            size="small"
            type="text"
            @click="showDoneList(row.instanceId, row.formPath, row.infoVo)"
            v-hasPermi="['flow:execute:doneList']"
          >审批记录</el-button>
          <el-button
            size="small"
            type="text"
            @click="toFlowImage(row.instanceId)"
          >流程图</el-button>
          <el-button
            size="small"
            type="text"
            v-if="row.ext"
            @click="handleView(row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 流程图弹窗 -->
    <el-dialog title="流程图" v-model="flowChartVisible" width="70%" append-to-body>
      <warm-chart :insId="currentInstanceId" />
    </el-dialog>

    <!-- 动态组件弹窗 -->
    <el-dialog
      :title="dynamicDialogTitle"
      v-model="dynamicDialogVisible"
      :width="dynamicDialogWidth"
      append-to-body
    >
      <component
        :is="dynamicComponent"
        v-if="dynamicComponent"
        :infoVo="currentInfoVo"
        :taskId="currentTaskId"
        :disabled="false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, defineAsyncComponent, getCurrentInstance} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Search, Refresh } from '@element-plus/icons-vue';
import { donePage } from '@/api/flow/execute';
import WarmChart from '@/views/flow/definition/warm_chart.vue';
import { parseTime } from '@/utils/ruoyi';

const {proxy} = getCurrentInstance();
const router = useRouter();

// 字典数据
const {flow_status} = proxy.useDict("flow_status")
// 状态管理
const loading = ref(false);
const showSearch = ref(true);
const flowChartVisible = ref(false);
const dynamicDialogVisible = ref(false);
const dynamicComponent = ref(null);
const dynamicDialogTitle = ref('审批详情');
const dynamicDialogWidth = ref('80%');

// 数据相关
const instanceList = ref([]);
const total = ref(0);
const currentInstanceId = ref(null);
const currentTaskId = ref(null);
const currentInfoVo = ref(null);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  nodeName: null,
  flowStatus: null,
  createBy: null,
  createTime: null
});

// 查询流程实例列表
const getList = async () => {
  try {
    loading.value = true;
    const { rows, total: totalCount } = await donePage(queryParams);
    instanceList.value = rows;
    total.value = totalCount;
  } catch (error) {
    ElMessage.error('获取数据失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryParams.nodeName = null;
  queryParams.flowStatus = null;
  queryParams.createTime = null;
  handleQuery();
};

// 审批记录操作
const showDoneList = (instanceId, formPath, infoVo) => {
  router.push({
    path: `/done/doneList/index/${instanceId}`,
    query: {
      disabled: false,
      pageNum: queryParams.pageNum,
      formPath,
      infoVo: JSON.stringify(infoVo || {})
    }
  });
};

// 查看流程图
const toFlowImage = (instanceId) => {
  currentInstanceId.value = instanceId;
  flowChartVisible.value = true;
};

// 处理查看操作
const handleView = (row) => {
  currentTaskId.value = row.id;

  // 解析扩展数据
  if (row.ext) {
    try {
      currentInfoVo.value = JSON.parse(row.ext);
    } catch (e) {
      console.error('解析扩展数据失败:', e);
      currentInfoVo.value = {};
    }
  }

  // 动态加载组件
  if (row.formPath) {
    dynamicComponent.value = defineAsyncComponent(() =>
      import(`@/views/${row.formPath}`).catch(() =>
        import('@/views/error/404.vue')
      )
    );
    dynamicDialogVisible.value = true;
  } else {
    ElMessage.warning('未配置表单路径');
  }
};

// 初始化加载数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.fixed-width {
  width: 180px;
}
</style>
